package posts

import (
	"community-service/cmd/api/internal/models/model"
	"community-service/cmd/api/internal/svc"
	"community-service/cmd/api/internal/types"
	e "community-service/pkg/errorx"
	"context"
	"google.golang.org/grpc/codes"
	"gorm.io/gorm"

	"github.com/zeromicro/go-zero/core/logx"
)

type BanedPostLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewBanedPostLogic(ctx context.Context, svcCtx *svc.ServiceContext) *BanedPostLogic {
	return &BanedPostLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *BanedPostLogic) BanedPost(req *types.PostBanedReq) (resp *types.Empty, err error) {

	if req.Reason == "" {
		return nil, e.NewGrpcErr(codes.InvalidArgument, e.ErrorParam)
	}

	postQuery := l.svcCtx.DB.WithContext(l.ctx).Model(&model.CsCommunityPost{})

	// 检查帖子是否存在
	var existPost model.CsCommunityPost
	if err = postQuery.Session(&gorm.Session{}).Where("id = ?", req.Id).Find(&existPost).Error; err != nil {
		return nil, e.NewGrpcErr(codes.Internal, e.DBError)
	}

	if existPost.ID == 0 {
		return nil, e.NewGrpcErr(codes.NotFound, e.PostNotFound)
	}

	// 设置为隐藏状态 (status=2) 并记录禁止原因
	updateData := map[string]interface{}{
		"status": types.PostTypeHide,
		"reason": req.Reason,
	}

	if err = postQuery.Session(&gorm.Session{}).Where("id = ?", req.Id).Updates(updateData).Error; err != nil {
		return nil, e.NewGrpcErr(codes.Internal, e.DBError)
	}

	return &types.Empty{}, nil
}
